package com.seven.restaurant.annotation.validator;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.seven.restaurant.annotation.ExistId;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Objects;

/**
 * 主键存在效验实现类
 *
 * @author BaiBan
 * @since 2022/8/4
 */
public class ExistIdValidator implements ConstraintValidator<ExistId, Long> {

    //该注解自动匹配sqlSession对应的引用
    @Autowired
    private SqlSessionTemplate sqlSession;

    private BaseMapper<?> mapper;

    @Override
    public void initialize(ExistId ExistId) {
        mapper = sqlSession.getMapper(ExistId.value());
    }

    @Override
    public boolean isValid(Long id, ConstraintValidatorContext constraintValidatorContext) {
        return Objects.nonNull(mapper.selectById(id));
    }
}
